<template>
  <!-- :bodyStyle="{ height: '150px' }" -->
  <a-modal
    :title="title"
    width="25%"
    :visible="visible"
    :confirmLoading="loading"
    :footer="null"
    @cancel="
      () => {
        this.visible = false
      }
    "
  >
    <template>
      <a-spin :spinning="loading">
        <a-form-model ref="form" :model="entity" v-bind="layout">
          <a-form-model-item label="导入类型" prop="DrModel" v-if="showSelect">
            <a-select style="width: 100%" v-model="DrModel">
              <a-select-option value="Import">设计清单</a-select-option>
              <a-select-option value="ImportOrder">补加单</a-select-option>
              <a-select-option value="ChangeOrder">变更单</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="项目:" prop="ProjectId" v-if="showSelect">
            <ProjectSelect v-model="entity.ProjectId" @select="project"></ProjectSelect>
          </a-form-model-item>
          <a-form-model-item label="楼号：" prop="BuildingNumberID" v-if="showSelect">
            <a-select style="width: 100%" @change="changelohao" v-model="entity.BuildingNumberID" allowClear>
              <a-select-option v-for="(item, index) in lohao" :key="index" :value="item.Id">
                {{ item.Buildingnumber }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-form-model>
      </a-spin>

      <a-row :gutter="10" style="margin-top: 30px">
        <a-col
          :span="templet != '/PB/PB_DesignList/ExportToExcel' ? 12 : 24"
          :style="templet != '/PB/PB_DesignList/ExportToExcel' ? '' : 'text-align: center;'"
        >
          <!-- :md="14" :sm="24" -->
          <a-upload name="file" :beforeUpload="beforeUpload" :multiple="true" :action="action" @change="handleChange">
            <a-button type="primary"> <a-icon type="upload" /> 上传数据 </a-button>
          </a-upload>
        </a-col>

        <a-col :span="12" style="text-align: right" v-show="templet != '/PB/PB_DesignList/ExportToExcel'">
          <a-button
            @click="
              () => {
                this.visible = false
              }
            "
            ><a-icon type="download" />

            <a @click="LoadClick($rootUrl + templet)">下载模板表</a>
            <!--  -->
          </a-button>
        </a-col>
      </a-row>
    </template>
  </a-modal>
</template>

<script>
import Token from '@/utils/cache/TokenCache'
import { download } from '@/components/download'
export default {
  components: {
    Token
    // ProjectSelect
  },
  rules: {
    // DrModel: [{ required: true, validator: this.validatePass1, trigger: 'change' }],
    ProjectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
    BuildingNumberID: [{ required: true, message: '请选择楼号', trigger: 'change' }]
  },
  props: {
    parentObj: Object,
    // rootUrl:$rootUrl,
    leading: { type: String, required: false },
    templet: { type: String, required: false }
  },
  data() {
    return {
      DrModel: '',
      showSelect: false,
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      lohao: [],
      name: '',
      visible: false,
      loading: false,

      title: '',

      entity: {
        ProjectId: ''
      }
    }
  },
  computed: {
    action() {
      if (this.showSelect && this.DrModel) {
        if (this.DrModel == 'Import')
          return `${this.$rootUrl}/PB/PB_DesignList/Import?ProjectId=${this.entity.ProjectId}&BuildingNumberID=${
            this.entity.BuildingNumberID
          }`
        else if (this.DrModel == 'ImportOrder')
          return `${this.$rootUrl}/PB/PB_DesignList/ImportOrder?ProjectId=${this.entity.ProjectId}&BuildingNumberID=${
            this.entity.BuildingNumberID
          }`
        else if (this.DrModel == 'ChangeOrder')
          return `${this.$rootUrl}/PB/PB_DesignList/ImportChangeOrder?ProjectId=${
            this.entity.ProjectId
          }&BuildingNumberID=${this.entity.BuildingNumberID}`
      } else {
        return this.leading == '/PB/PB_DesignList/Import'
          ? `${this.$rootUrl}/PB/PB_DesignList/Import?ProjectId=${this.entity.ProjectId}&BuildingNumberID=${
              this.entity.BuildingNumberID
            }`
          : this.$rootUrl + this.leading
      }
    }
  },
  methods: {
    validatePass1(rule, value, callback) {
      if (this.DrModel) callback()
      else callback(new Error('请选择导入类型'))
    },
    beforeUpload(file, fileList) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          if (!valid) {
            reject()
          } else {
            resolve()
          }
        })
      })
    },

    project(row) {
      this.lohao = []
      delete this.entity.BuildingNumberID
      this.Getlohao(row.Id)
      //console.log(row.Id)
    },

    init() {
      this.visible = true
    },
    openForm(id, title, name, DrModel) {
      // //console.log(name)
      this.init()
      this.title = title
      this.name = name
      if (DrModel) this.showSelect = true
      else this.showSelect = false
    },
    handleChange(info) {
      //console.log(info)
      //   if (this.templet == '/PB/PB_DesignList/ExportToExcel') {
      //     // var str = `/PB/PB_DesignList/ExportToExcel?ProjectId=${this.entity.ProjectId}&BuildingNumberID=${this.entity.BuildingNumberID}`
      //     // //console.log(str)
      //     // this.templet = str
      //   }
      if (info.file.status !== 'uploading') {
        //console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response.Success === false) {
          let str = info.file.response.Msg
          let str1 = str.split(',').join('\n')
          this.$message.error(`${info.file.name}文件,${str1},请检查文件内容！ `)
          this.exportRaw('错误内容.txt', str1)
        } else {
          this.$message.success(`${info.file.name}  文件上传成功！`)
        }
        this.visible = false
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 文件上传失败！`)
      }
    },
    LoadClick(url) {
      //console.log(this.name)
      download(url, this.name)
    },
    fakeClick(obj) {
      var ev = document.createEvent('MouseEvents')
      ev.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
      obj.dispatchEvent(ev)
    },
    exportRaw(name, data) {
      var urlObject = window.URL || window.webkitURL || window
      var export_blob = new Blob([data])
      var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
      save_link.href = urlObject.createObjectURL(export_blob)
      save_link.download = name
      this.fakeClick(save_link)
    }
  },
  watch: {
    leading(a) {
      //console.log(a)
      // if (a == '/PB/PB_DesignList/Import') {
      //   this.leading = `/PB/PB_DesignList/Import?ProjectId=${this.entity.ProjectId}&BuildingNumberID=${this.entity.BuildingNumberID}`
      // }
    },
    'entity.ProjectId': {
      handler(newVal, oldVal) {
        if (newVal && !oldVal) {
          this.$refs['form'].fields.forEach(filed => {
            if (filed.prop == 'ProjectId') {
              filed.clearValidate()
            }
          })
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>
